package com.ptp.handler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ptp.chat.MessageInfo;
import com.ptp.manage.ChannelManage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/** 
 * @author liningning 
 * @date 2018年12月4日 下午2:46:58 
*/
public class PushHandler extends ChannelInboundHandlerAdapter{

	private Logger logger = LoggerFactory.getLogger(PushHandler.class);
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info(ctx.channel().remoteAddress()+"连接服务器成功");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//在线消息广播
		MessageInfo mesInfo = JSON.parseObject(msg.toString(),MessageInfo.class);
		ChannelManage.messages.put(mesInfo.getMessage().getId(), mesInfo.getMessage());
		ChannelManage.channels.entrySet().stream().forEach(ele -> {
			//转码 TODO
			ele.getValue().writeAndFlush(new TextWebSocketFrame(mesInfo.getMessage().getContent()));
			mesInfo.setChannel(ele.getValue());
			mesInfo.setIpaddr(ele.getValue().remoteAddress().toString());
			ChannelManage.received.put(ele.getKey()+mesInfo.getMessage().getId(), mesInfo);
		});
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.info("服务处理异常"+ctx.channel().remoteAddress());
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		//IP加入服务器 用户在线
		ChannelManage.channels.put(ctx.channel().remoteAddress().toString(), ctx.channel());
		ChannelManage.messages.entrySet().stream().forEach(ele -> {
			if(!ChannelManage.isReceived(null, ctx.channel().remoteAddress().toString(),ele.getKey())) {
				ctx.channel().writeAndFlush(ele.getValue());
			}
		});
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		ChannelManage.channels.remove(ctx.channel().remoteAddress().toString());
	}

	
}
